<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use \App\Home\Member;
use \App\Home\Laravel_sms;
use Auth;
use Validator;
use Input;
use SmsManager;
class PublicController extends Controller
{
    public function login(){
    	return view('home.public.login');
    }

    //验证用户登录
    public function checkLogin(Request $request){
    	//验证数据的基本有效性
    	$this -> validate($request,[
    			'mobile'	=>	'required|min:11|max:11',
    			'password'	=>	'required|min:6|max:20',
    			//'captcha'	=>	'required|size:5|captcha',
    		]);
		$member = Member::where("mobile",$request -> mobile) -> value('id');
		if(empty($member) == true){
			$res = array(
					'error' => true,
					'errorMessage' => '此用户未注册'
			);
			return response() -> json($res);
		}
    	//将用户提供的用户名和密码进行验证
    	$data = $request -> only('mobile','password');
    	//通过auth验证
    	$result = Auth::guard('home') -> attempt($data);
    	// dd($result);
    	if($result){
    		//验证成功
			$res = array(
				'success' => true,
			);
			return response() -> json($res);
    	}else{
    		//验证失败
			$res = array(
				'error' => true,
				'errorMessage' => '用户名或密码错误'
			);
			return response() -> json($res);
    	}
    }

	public function register(){
		return view('home.public.register');
	}

	//发送手机验证码
	public function validateSmsCode()
	{
		// 获取全部提交数据
		$data = Input::all();
		// 开始验证
		$validator = Validator::make($data, [
				'phone' => 'required|zh_mobile|size:11',
				'captcha'	=>	'required|size:4|captcha',
		]);
		if ($validator->fails()) {
			// 验证失败
			// 获取错误消息
			$errors = $validator->messages() -> toArray();
			$result['success'] = false;
			foreach($errors as $key => $value){
				if(is_array($value) == true){
					foreach($value as $k => $v){
						$result['errorMessage'][] = $v;
					}
				}else{
					$result['errorMessage'][] = $value;
				}
			}
			// 构造 JSON 响应
			return response() -> json($result);
		}else{
			// 验证通过
			$result = SmsManager::validateSendable();
			if(!$result['success']) {
				return response() -> json($result);
			}
			$result = SmsManager::validateFields();
			if(!$result['success']) {
				return response() -> json($result);
			}
			$result = SmsManager::requestVerifySms();
			if(!$result['success']) {
				return response() -> json($result);
			}
			return response() -> json($result);
		}
	}

	//手机验证码登录
	public function loginCode(){
		//验证数据
		$data = Input::all();
		$mobile = $data['username'];
		$password = Member::where("mobile",$mobile) -> value('plaintext_password');
		if(empty($password) == true){
			$res = array(
					'error' => true,
					'errorMessage' => '此用户未注册'
			);
			return response() -> json($res);
		}

		$validator = Validator::make($data, [
//				'username' => 'required|confirm_mobile_not_change|confirm_rule:mobile_required',
				'vcode' => 'required|size:4|captcha',
//				'code'  => 'required|verify_code',
		]);

		if ($validator->fails()) {

			//SmsManager::forgetState(); //验证失败后建议清空存储的发送状态，防止用户重复试错
			$errors = $validator->messages() -> toArray();
			$result['success'] = false;
			$result['errorMessage'] = '';
			foreach($errors as $key => $value){
				if(is_array($value) == true){
					$result['errorMessage'] = $value[0];//错误信息只获取第一条
				}else{
					$result['errorMessage'] = $value;
				}
			}
			// 构造 JSON 响应
			return response() -> json($result);
		}else{
			//上面的手机号验证码一直不成功，所以使用查询数据库的方式验证 start
			$sms = Laravel_sms::where('to',$data['username']) -> orderBy('id','desc') -> first();
			if($sms){
				$sent_time = $sms -> sent_time;
				if(time() > ($sent_time + 300)){
					Laravel_sms::where('id',$sms['id']) -> delete();//清除失效验证码
					$res = array(
							'error' => true,
							'errorMessage' => '动态验证码已失效'
					);
					return response() -> json($res);
				}else{
					$code = json_decode($sms -> data,true);
					if($data['code'] != $code['code']){
						$res = array(
								'error' => true,
								'errorMessage' => '动态验证码错误1'
						);
						return response() -> json($res);
					}else{
						//通过auth验证
						$result = Auth::guard('home') -> attempt(['mobile' => $mobile,'password' => $password]);
						if($result){
							//验证成功
							Laravel_sms::where('id',$sms['id']) -> delete();//清除验证码
							$res = array(
									'success' => true,
							);
							return response() -> json($res);
						}else{
							//验证失败
							$res = array(
									'error' => true,
									'errorMessage' => '登录失败'
							);
							return response() -> json($res);
						}
					}

				}

			}else{
				$res = array(
						'error' => true,
						'errorMessage' => '动态验证码错误2'
				);
				return response() -> json($res);
			}

		}
	}

	//注册验证手机号码
	public function valiAccount(){
		$mobile = Input::get('username');
		$res = Member::where("mobile",$mobile) -> value('id');
		$res = [
			'success' => true,
			'resultObject' => $res == null ? 200 : 400
		];
		return response() -> json($res);

	}

	public function logout(){
		Auth::guard('home') -> logout();
	}

	public function phoneRegist(){
		$data = Input::all();
		$user = Member::where("mobile",$data['username']) -> first();
		if(empty($user) == true){
			$validator = Validator::make($data, [
				'username' => 'required|zh_mobile',
				'vcode' => 'required|size:4|captcha',
			]);
			if ($validator->fails()) {
				$errors = $validator -> messages() -> toArray();
				$result['success'] = false;
				$result['errorMessage'] = '';
				foreach($errors as $key => $value){
					if(is_array($value) == true){
						$result['errorMessage'] = $value[0];//错误信息只获取第一条
					}else{
						$result['errorMessage'] = $value;
					}
				}
				return response() -> json($result);
			}else{
				$sms = Laravel_sms::where('to',$data['username']) -> orderBy('id','desc') -> first();
				if($sms){
					$sent_time = $sms -> sent_time;
					if(time() > (time() + 300)){
						Laravel_sms::where('id',$sms['id']) -> delete();//清除失效验证码
						$res = array(
								'error' => true,
								'errorMessage' => '动态码超时，请重新发送！'
						);
						return response() -> json($res);
					}else{
						$code = json_decode($sms -> data,true);
						if($data['code'] != $code['code']){
							$res = array(
									'error' => true,
									'errorMessage' => '动态验证码错误1'
							);
							return response() -> json($res);
						}else{
							$res = Member::insert([
								'username' => $data['username'],
								'password' => password_hash($data['password'],PASSWORD_DEFAULT),
								'plaintext_password' => $data['password'],
								'mobile'   => $data['username'],
								'third_party_type' => 1,
							]);
							if($res){
								//通过auth验证
								$result = Auth::guard('home') -> attempt(['mobile' => $data['username'],'password' => $data['password']]);
								if($result){
									//验证成功
									Laravel_sms::where('id',$sms['id']) -> delete();//清除验证码
									$res = array(
											'success' => true,
									);
									return response() -> json($res);
								}else{
									//验证失败
									$res = array(
											'error' => true,
											'errorMessage' => '登录失败'
									);
									return response() -> json($res);
								}
							}else{
								$res = array(
										'error' => true,
										'errorMessage' => '添加用户失败'
								);
								return response() -> json($res);
							}
						}

					}

				}else{
					$res = array(
							'error' => true,
							'errorMessage' => '动态验证码错误2'
					);
					return response() -> json($res);
				}
			}
		}else{
			$res = array(
					'error' => true,
					'errorMessage' => '此手机号已被注册'
			);
			return response() -> json($res);
		}
	}
}
